package com.aegis.manage.schedules;

import cn.hutool.core.collection.CollectionUtil;
import com.aegis.common.master.redis.main.NodeManager;
import com.aegis.core.dao.AegisDao;
import com.aegis.core.manager.AegisAppManager;
import com.aegis.core.manager.AegisComponentManager;
import com.aegis.core.model.AegisAppInfo;
import com.aegis.manage.model.dos.AuthApp;
import com.aegis.manage.service.auth.app.AuthAppService;
import com.aegis.manage.service.auth.user.UserPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;


@EnableScheduling
@Slf4j
@Service("scheduleTaskService")
public class ScheduleTaskService {

    @Autowired
    private AuthAppService authAppService;

    @Autowired
    private UserPermissionService userPermissionService;

    @Autowired
    private AegisDao aegisDao;

    @PostConstruct
    public void init() {
        AegisComponentManager.initAegisDao(aegisDao);
        refreshAppInfo();
    }


    /**
     * 每隔1分钟执行一次，将应用信息刷回缓存，防止开发者直接操作数据库导致缓存数据不一致
     * 正常情况下，开发者不需要定时器去同步数据库和缓存的数据
     * 不需要额外做加锁操作，保证最终一致性即可，最差情况是有1分钟数据不一致
     */
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void syncLoginUser() {
        if (!NodeManager.getInstance().isMaster()) {
            return;
        }
        log.info("开始同步登录用户信息");
        userPermissionService.syncLoginUser();
    }



    /**
     * 每隔1分钟执行一次，将应用信息刷回缓存，防止开发者直接操作数据库导致缓存数据不一致
     * 正常情况下，开发者不需要定时器去同步数据库和缓存的数据
     * 不需要额外做加锁操作，保证最终一致性即可，最差情况是有1分钟数据不一致
     */
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void refreshAppInfo() {
        List<AuthApp> authApps =
                authAppService.selectAllApps();
        if (CollectionUtil.isEmpty(authApps)) {
            return;
        }
        AegisAppManager.addAppInfos(authApps.stream().map(sysAppDO -> {
            AegisAppInfo aegisAppInfo = new AegisAppInfo();
            aegisAppInfo.setAppId(sysAppDO.getAppId());
            aegisAppInfo.setName(sysAppDO.getAppName());
            return aegisAppInfo;
        }).collect(Collectors.toList()));
    }


}
